<?php
session_start();
$hasRight=isset($_GET['xh'])?($_SESSION['user']['xh']===$_GET['xh'] or $_SESSION['user']['isAdmin
']):true;
$db = new PDO('mysql:host=localhost;dbname=db2', 'root', '12qwas');
try {
    if($_POST){
        $xh=$_POST['xh'];
        $name=$_POST['name'];
        $tel=$_POST['tel'];
        $pwd=$_POST['pwd'];
        if($pwd!==$_POST['pwd2'])throw new Exception('两次输入的口令不一致~');
        if($pwd){ //用户输入有新的口令，那就判断是否能满足规则要求，用正则表达式就比较方便
            preg_match('/^(?=.*?\d)(?=.*?[a-z])(?=.*?[^0-9a-z]).{3,20}$/i',$pwd,$matches);
            if(!$matches)throw new Exception('口令不能满足规则要求~');
        }else if(isset($_GET['xh'])){ //修改用户信息但没有提供新口令
            $pwd=$_SESSION['user']['pwd']; //将保持原来的口令不变
        }else{ //注册新用户却没有输入口令
            throw new Exception('必须设置口令信息~');
        }
        if(isset($_GET['xh'])) { // URL 参数中包含 xh，说明是更新用户信息
            if($hasRight) {
                $r['isAdmin']=$_SESSION['user']['isAdmin'];
                unset($r['pwd2']);
            }
            if(!$hasRight)throw new Exception('Sorry，你没有操作的权限~');
            $st = $db->prepare("update students set xh=?,name=?,tel=?,pwd=? where xh=?");
            $st->execute(array($xh, $name, $tel, $pwd, $_GET['xh']));
            $_SESSION['user']=[ ...$_SESSION['user'], 'xh'=>$xh, 'name'=>$name, 'tel'=>$tel, 'pwd'=>$pwd ];
 }else{
            $st = $db->prepare("insert into students(xh,name,tel,pwd) values (?,?,?,?)");
            $st->execute(array($xh, $name, $tel, $pwd));
        }
        header("Location: index.php?pos=".$_GET['pos']) or die();
    }elseif (isset($_GET['xh'])) {
        $st=$db->prepare("select * from students where xh=?");
        $st->execute(array($_GET['xh']));
        $r=$st->fetch(PDO::FETCH_ASSOC); //成功返回数组，失败返回 false
        $xh = $r['xh']; // 获取学号，或是 NULL
        $name = $r['name'];
        $tel = $r['tel'];
    }
}catch(Exception $e){
    $msg=$e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title><?= isset($_GET['xh'])?'修改':'注册新' ?>用户信息</title>
    <style>
        h1, b{ color:red; }
        input{ padding:10px; margin: 5px 0; border-radius: 8px; }
        .msg{ color:red; margin:10px 0; }
    </style>
</head>
<body>
<h1><?= isset($_GET['xh'])?'修改':'注册新' ?>用户信息</h1>
<form method="post" >
    学号：<input name="xh" value="<?= $xh ?>"<?= $hasRight?"":" disabled" ?> /><br>
    姓名：<input name="name" value="<?= $name ?>"<?= $hasRight?"":" disabled" ?> /><br>
    电话：<input name="tel" value="<?= $tel ?>"<?= $hasRight?"":" disabled" ?> /><br>
    口令：<input name="pwd" type="password"<?= $hasRight?"":" disabled" ?> /> <b><?=
        isset($_GET['xh'])&&!$msg?'留空将不会修改原来的口令~':'3~20 个字符，须同时包含字母、数字及其他字符'
        ?></b><br>
    再次：<input name="pwd2" type="password"<?= $hasRight?"":" disabled" ?> /><br>
    <div class="msg"><?= $msg ?></div>
    <input type="submit" value=" 提交数据 "<?= $hasRight?"":" disabled" ?> />
</form>
</body>
</html>